<template>
  <div v-if="modelValue" class="dialog-overlay">
    <div class="dialog-content">
      <div class="dialog-header">
        <h3>生成子客登录链接</h3>
        <button class="close-btn" @click="closeDialog">&times;</button>
      </div>

      <div class="dialog-body">
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label for="proxyOrganizationOpenId">子客企业ID *</label>
            <input
              type="text"
              id="proxyOrganizationOpenId"
              v-model="formData.proxyOrganizationOpenId"
              placeholder="请输入子客企业ID(初次注册的企业需自定义一个唯一代号，如org_XXXX)"
              required
            />
          </div>

          <div class="form-group">
            <label for="proxyOrganizationName">子客企业名称 *</label>
            <input
              type="text"
              id="proxyOrganizationName"
              v-model="formData.proxyOrganizationName"
              placeholder="请输入子客企业名称(需与营业执照上的名称一致)"
            />
          </div>
          <div class="form-group">
            <label for="operatorId">操作员ID *</label>
            <input type="text" id="operatorId" v-model="formData.operatorId" placeholder="请输入操作员ID" required />
          </div>
          <div class="form-group">
            <label for="operatorName">操作员姓名 *</label>
            <input type="text" id="operatorName" v-model="formData.operatorName" placeholder="请输入操作员姓名" required />
          </div>
          <div class="form-group">
            <label for="operatorTel ">操作员电话 *</label>
            <input type="text" id="operatorTel" v-model="formData.operatorTel" placeholder="请输入操作员电话" required />
          </div>

          <!--          <div class="form-group">
            <label for="loginType">登录终端</label>
            <select id="loginType" v-model="formData.loginType">
              <option value="1">PC端</option>
              <option value="2">移动端</option>
            </select>
          </div>

          <div class="form-group">
            <label for="expiresIn">有效期(秒)</label>
            <input
                type="number"
                id="expiresIn"
                v-model="formData.expiresIn"
                placeholder="默认3600秒(1小时)"
                min="300"
            />
          </div>-->

          <div class="form-actions">
            <button type="button" @click="closeDialog" class="cancel-btn">取消</button>
            <button type="submit" :disabled="isLoading">
              {{ isLoading ? '生成中...' : '生成链接' }}
            </button>
          </div>
        </form>
      </div>
      <div v-if="resultUrl" class="result-section">
        <h4>生成成功!链接生成时间：{{ formattedTime }}</h4>
        <h4 :style="{ fontWeight: 'bold' }">注意：链接有效期‌为30分钟‌，超时未登录将失效，需重新生成</h4>
        <div class="result-url">
          <a :href="resultUrl" target="_blank">{{ resultUrl }}</a>
          <button @click="copyUrl" class="copy-btn">复制</button>
        </div>
      </div>

      <div v-if="error" class="error-message">
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, computed } from 'vue';
  import { tencentEsignApi } from '../TencentConsoleloginurlInfo.api';
  import { Result } from '#/axios';

  const props = defineProps({
    modelValue: Boolean,
  });

  const emit = defineEmits(['update:modelValue', 'success']);
  // 表单状态
  const formData = ref({
    proxyOrganizationOpenId: '',
    proxyOrganizationName: '',
    operatorId: '',
    operatorName: '',
    operatorTel: '',
    loginType: '1',
    expiresIn: 3600,
  });
  const currentTime = ref(new Date());
  // 格式化时间为 "YYYY年MM月DD日 HH时mm分ss秒"
  const formatTime = (date) => {
    date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day}- ${hours}:${minutes}:${seconds}`;
  };
  const formattedTime = ref('');

  const resultUrl = ref('');
  const error = ref('');
  const isLoading = ref(false);
  // 定义响应数据
  const resultData = ref<Result<string>>();
  const closeDialog = () => {
    emit('update:modelValue', false);
    // 重置表单
    setTimeout(() => {
      formData.value = {
        proxyOrganizationOpenId: '',
        proxyOrganizationName: '',
        operatorId: '',
        operatorName: '',
        operatorTel: '',
        loginType: '1',
        expiresIn: 3600,
      };
      resultUrl.value = '';
      error.value = '';
    }, 300);
  };

  const submitForm = async () => {
    if (isLoading.value) return;

    isLoading.value = true;
    error.value = '';
    resultUrl.value = '';
    // 构造请求参数实体
    const params = {
      proxyOrganizationOpenId: formData.value.proxyOrganizationOpenId,
      proxyOrganizationName: formData.value.proxyOrganizationName,
      operatorId: formData.value.operatorId,
      operatorName: formData.value.operatorName,
      operatorTel: formData.value.operatorTel,
    };

    try {
      //  调用API  替换为你的实际API端点
      tencentEsignApi(params).then((response) => {
        // 经过异步处理后，将响应数据赋值给result
        resultData.value = response;
        if (resultData.value != '' && resultData.value != null) {
          currentTime.value = computed(() => {
            return new Date();
          });
          // 计算属性，返回格式化后的时间
          formattedTime.value = formatTime(currentTime.value);
          resultUrl.value = resultData.value;
          emit('success', resultUrl.value, formData.value.proxyOrganizationName || formData.value.proxyOrganizationOpenId);
        } else {
          error.value = '生成链接失败!';
        }
      });
    } catch (err) {
      error.value = '请求失败: ' + (err.response?.data?.message || err.message);
      console.error('API请求错误:', err);
    } finally {
      isLoading.value = false;
    }
  };

  const copyUrl = () => {
    if (!resultUrl.value) return;

    navigator.clipboard
      .writeText(resultUrl.value)
      .then(() => alert('链接已复制到剪贴板'))
      .catch((err) => {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
      });
  };

  // 监听对话框关闭
  watch(
    () => props.modelValue,
    (newVal) => {
      if (!newVal) {
        closeDialog();
      }
    }
  );
</script>

<style scoped>
  .dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .dialog-content {
    background: white;
    border-radius: 8px;
    width: 500px;
    max-width: 90%;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #f0f0f0;
    background-color: #059669;
  }

  .dialog-header h3 {
    margin: 0;
    color: white;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #999;
    padding: 0;
    line-height: 1;
  }

  .dialog-body {
    padding: 24px;
  }

  .form-group {
    margin-bottom: 16px;
    display: grid;
    grid-template-columns: auto 1fr; /* 第一列宽度自动，第二列剩余空间 */
    align-items: center; /* 垂直居中对齐 */
    gap: 10px; /* 根据需要调整间距 */
  }

  .form-group label {
    margin-bottom: 8px;
    font-weight: 500;
  }

  .form-group input,
  .form-group select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    box-sizing: border-box;
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 24px;
  }

  .form-actions button {
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
  }

  .form-actions button[type='submit'] {
    background-color: #059669;
    color: white;
    border: none;
  }

  .form-actions button[type='submit']:hover {
    background-color: #059669;
  }

  .form-actions button[type='submit']:disabled {
    background-color: #d9d9d9;
    cursor: not-allowed;
  }

  .cancel-btn {
    background-color: white;
    border: 1px solid #d9d9d9;
  }

  .cancel-btn:hover {
    border-color: #1890ff;
    color: #1890ff;
  }

  .result-section {
    margin-top: 10px;
    padding: 16px;
    background-color: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 4px;
  }

  .result-section h4 {
    margin-top: 0;
    color: #52c41a;
  }

  .result-url {
    display: flex;
    align-items: center;
    margin-top: 8px;
  }

  .result-url a {
    flex: 1;
    color: #1890ff;
    word-break: break-all;
  }

  .copy-btn {
    margin-left: 8px;
    padding: 4px 8px;
    background-color: #52c41a;
    color: white;
    border: none;
    border-radius: 2px;
  }

  .error-message {
    margin-top: 16px;
    padding: 8px 16px;
    background-color: #fff1f0;
    border: 1px solid #ffa39e;
    border-radius: 4px;
    color: #f5222d;
  }
</style>
